package com.sanley.piss.web.controller;

import com.github.pagehelper.PageInfo;
import com.sanley.piss.mapper.ArchivesMapper;
import com.sanley.piss.mapper.BasicInfoMapper;
import com.sanley.piss.mapper.DictionaryDataMapper;
import com.sanley.piss.mapper.UserMapper;
import com.sanley.piss.model.exceptionUtil.json.JsonResult;
import com.sanley.piss.model.po.*;
import com.sanley.piss.model.vo.BasicExportVO;
import com.sanley.piss.model.vo.BasicInfoVO;
import com.sanley.piss.web.excel.ExcelService;
import com.sanley.piss.web.excel.FilePortUtil;
import com.sanley.piss.web.service.mapper.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Create By  on 2021/3/22.
 *
 * @author 张凯大天才
 */

@Api(value = "员工基本信息controller", tags = "员工基本信息表操作接口")
@RestController
@RequestMapping("basicInfo")
public class BasicInfoController extends AbstractController {
    @Autowired
    private IBasicInfoService service;
    @Autowired
    private BasicInfoMapper basicInfoMapper;
    @Autowired
    private DictionaryDataMapper dataMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ExcelService excelService;
    @Autowired
    private IFamilyService familyService;
    @Autowired
    private ArchivesMapper archivesMapper;
    @Autowired
    private IArchivesService archivesService;
    @Autowired
    private IWorkExperienceService workExperienceService;
    @Autowired
    private IEducationalBackgroundService educationalBackgroundService;

    @ApiOperation(value = "根据当前用户ID插入一条记录")
    @RequestMapping(value = "/insert", method = RequestMethod.PUT)
    public JsonResult<Object> insert(@Valid BasicInfoVO info) {
        service.insert(info, getCurrentUserId());
        return JsonResult.success();
    }

    @ApiOperation(value = "根据ID删除多条记录")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.DELETE)
    public JsonResult delete(@PathVariable("ids") Integer[] ids) {
        service.removeByIds(ids);
        return JsonResult.success();
    }

    @ApiOperation(value = "根据ID修改一条记录")
    @ApiImplicitParam(name = "id", value = "根据id修改", dataType = "Integer", paramType = "query")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResult update(@Valid BasicInfoVO info) {
        service.updateById(info);
        return JsonResult.success();
    }

    @ApiOperation(value = "修改部门")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "根据id修改", dataType = "Integer", paramType = "path")
            , @ApiImplicitParam(name = "orgName", value = "要更换的部门名字")})
    @RequestMapping(value = "/{id}/updateOrgByUserId", method = RequestMethod.POST)
    public JsonResult updateOrgByUserId(String orgName, @PathVariable("id") Integer id) {
        service.updateOrgByUserId(orgName, id);
        return JsonResult.success();
    }

    @ApiOperation(value = "查询该用户注册的一条ID记录")
    @RequestMapping(value = "/selectById", method = RequestMethod.GET)
    public JsonResult<BasicInfoVO> selectById(Integer id) {
        return JsonResult.success(service.selectById(id));
    }

    @ApiOperation(value = "查询该用户注册的所有用户记录")
    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    public JsonResult<List<BasicInfoVO>> selectAll() {
        return JsonResult.success(service.selectAll(getCurrentUserId()));
    }

    @RequiresPermissions(value = {"basic:page"}, logical = Logical.OR)
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ApiOperation(value = "总页面分页查询，需要资源 basic:page")
    public JsonResult<PageInfo<BasicInfoVO>> page(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "20") Integer pageSize) {
        return JsonResult.success(service.page(pageNum, pageSize));
    }

    @ApiOperation(value = "导出")
    @RequestMapping(value = "/fileport/{ids}", method = RequestMethod.GET)
    public void filePort(HttpServletResponse response, @PathVariable("ids") Integer[] ids) {
        //导出的表名
        String title = "测试导出员工基本信息";
        //表中第一行表头字段
        String[] headers = {"姓名", "性别", "部门", "岗位", "职务", "工号", "工龄", "手机号", "入职日期", "合同类型", "在职情况", "离职时间"};
        //实际数据结果集
        List<BasicExportVO> basicInfoVOS = basicInfoMapper.selectExport(ids);
        //具体需要写入excel需要哪些字段，这些字段取自UserReward类，也就是上面的实际数据结果集的泛型
        List<String> listColumn = Arrays.asList("name", "sex", "orgName", "position", "job", "jobNum", "seniority", "phoneNumber", "dateJoinedcom", "contractType", "workingConditions", "resignationTime");
        try {
            FilePortUtil.exportExcel(response, title, headers, basicInfoVOS, listColumn);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Transactional
    @ApiOperation(value = "导入")
    @ResponseBody
    @RequestMapping(value = "/input", method = RequestMethod.POST)
    public JsonResult inputFile(MultipartFile file) throws IOException, ParseException {
        InputStream input = file.getInputStream();
        System.out.println(input);
        Workbook workbook = new HSSFWorkbook(input);
        Sheet sheet = workbook.getSheetAt(0);
        List<BasicInfo> list = new ArrayList<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        int totalRows = sheet.getPhysicalNumberOfRows();
        int basicInfolast = 0;
        for (Row row : sheet) {
            basicInfolast = row.getRowNum();
            BasicInfo basicInfo = new BasicInfo();
            if (row.getRowNum() == 0) {
                continue;
            } else {
                String orgName = FilePortUtil.getValue(row.getCell(0));
                if (orgName.equals("姓名") || orgName.equals(" ")) {
                    break;
                }
                basicInfo.setUserId(userMapper.selectIdByOrgName(orgName));
                basicInfo.setName(FilePortUtil.getValue(row.getCell(1)));
                String sex = FilePortUtil.getValue(row.getCell(2));
                if (sex.equals("女")) {
                    basicInfo.setSex(0);
                } else {
                    basicInfo.setSex(1);
                }
                basicInfo.setAge((int) Double.parseDouble(FilePortUtil.getValue(row.getCell(3))));
                basicInfo.setHeight(new BigDecimal(FilePortUtil.getValue(row.getCell(4))));
                basicInfo.setWeight(new BigDecimal(FilePortUtil.getValue(row.getCell(5))));
                basicInfo.setBloodType(dataMapper.selectArchivesTypes(FilePortUtil.getValue(row.getCell(6)), "血型"));
                basicInfo.setBirthdayType(dataMapper.selectArchivesTypes(FilePortUtil.getValue(row.getCell(7)), "生日类型"));
                basicInfo.setBirthday(sf.parse(FilePortUtil.getValue(row.getCell(8))));
                basicInfo.setHobby(FilePortUtil.getValue(row.getCell(9)));
                basicInfo.setPhoneNumber(FilePortUtil.getValue(row.getCell(10)));
                basicInfo.setWechat(FilePortUtil.getValue(row.getCell(11)));
                basicInfo.setQq(FilePortUtil.getValue(row.getCell(12)));
                basicInfo.setEmail(FilePortUtil.getValue(row.getCell(13)));
                basicInfo.setEmpCloModel(FilePortUtil.getValue(row.getCell(14)));
                basicInfo.setEmpThose(new BigDecimal(FilePortUtil.getValue(row.getCell(15))));
                basicInfo.setEmpAllermedicine(FilePortUtil.getValue(row.getCell(16)));
                basicInfo.setEmpHousaddr(FilePortUtil.getValue(row.getCell(17)));
                basicInfo.setPositionId(dataMapper.selectArchivesTypes(FilePortUtil.getValue(row.getCell(18)), "岗位类型"));
                basicInfo.setJob(dataMapper.selectArchivesTypes(FilePortUtil.getValue(row.getCell(19)), "职位类型"));
                basicInfo.setJobNum(FilePortUtil.getValue(row.getCell(20)));
                basicInfo.setDateJoinedcom(sf.parse(FilePortUtil.getValue(row.getCell(21))));
                basicInfo.setWorkingConditions(dataMapper.selectArchivesTypes(FilePortUtil.getValue(row.getCell(22)), "在职情况"));
                basicInfo.setResignationTime(sf.parse(FilePortUtil.getValue(row.getCell(23))));
                basicInfo.setContractType(dataMapper.selectArchivesTypes(FilePortUtil.getValue(row.getCell(24)), "合同类型"));
                list.add(basicInfo);
            }
        }
        service.batchInsert(list);
        list.forEach(batchInfo -> {
            basicInfoMapper.updateSeniority(batchInfo.getId());
        });

        //添加家庭表
        int familyLast = 0;
        List<Family> familyList = new ArrayList<>();
        for (int numRow = basicInfolast + 1; numRow < totalRows; numRow++) {
            Family family = new Family();
            Row row = sheet.getRow(numRow);
            familyLast = row.getRowNum();
            System.out.println(familyLast);
            String employeeId = FilePortUtil.getValue(row.getCell(0));
            if (employeeId.equals("姓名") || employeeId.equals(" ")) {
                break;
            }
            family.setEmployeeId(basicInfoMapper.selectOrgBasicId(getCurrentUserId(), employeeId));
            family.setRealName(FilePortUtil.getValue(row.getCell(1)));
            family.setRelationId(dataMapper.selectArchivesTypes(FilePortUtil.getValue(row.getCell(2)), "家庭关系"));
            family.setMemberPhone(FilePortUtil.getValue(row.getCell(3)));
            family.setFamilyBirthday(sf.parse(FilePortUtil.getValue(row.getCell(4))));
            family.setMemberCloModel(FilePortUtil.getValue(row.getCell(5)));
            family.setMemberThose(FilePortUtil.getValue(row.getCell(6)));
            family.setMemberAllerm(FilePortUtil.getValue(row.getCell(7)));
            if (FilePortUtil.getValue(row.getCell(8)).equals("是")) {
                family.setEmpcom(0);
            } else {
                family.setEmpcom(1);
            }
            familyList.add(family);
        }
        familyService.datchInsert(familyList);

        //添加档案表
        int archivesLast = 0;
        List<Archives> archivesList = new ArrayList<>();
        for (int rowNum = familyLast + 1; rowNum < totalRows; rowNum++) {
            Archives archives = new Archives();
            Row row = sheet.getRow(rowNum);
            archivesLast = row.getRowNum();
            String employeeId = FilePortUtil.getValue(row.getCell(0));
            if (employeeId.equals("姓名") || employeeId.equals(" ")) {
                break;
            }
            archives.setEmployeeId(basicInfoMapper.selectOrgBasicId(getCurrentUserId(), employeeId));
            archives.setNation(FilePortUtil.getValue(row.getCell(1)));
            archives.setOrigo(FilePortUtil.getValue(row.getCell(2)));
            archives.setAccountType(dataMapper.selectArchivesTypes(FilePortUtil.getValue(row.getCell(3)), "户口类型"));
            archives.setDomicilePlace(FilePortUtil.getValue(row.getCell(4)));
            archives.setPoliticsStatus(FilePortUtil.getValue(row.getCell(5)));
            archives.setMaritalStatus(FilePortUtil.getValue(row.getCell(6)));
            archives.setIdNumber(FilePortUtil.getValue(row.getCell(7)));
            archives.setPositionChanges(FilePortUtil.getValue(row.getCell(8)));
            archives.setNowDept(FilePortUtil.getValue(row.getCell(9)));
            archives.setDateJoinedcom(sf.parse(FilePortUtil.getValue(row.getCell(10))));
            archives.setDateChange(sf.parse(FilePortUtil.getValue(row.getCell(11))));
            archives.setPositiveDates(sf.parse(FilePortUtil.getValue(row.getCell(12))));
            archives.setConcomDate(sf.parse(FilePortUtil.getValue(row.getCell(13))));
            archives.setEndDate(sf.parse(FilePortUtil.getValue(row.getCell(14))));
            archives.setCardNumber(FilePortUtil.getValue(row.getCell(15)));
            //加入list
            archivesList.add(archives);
        }
        archivesService.batchInsert(archivesList);
        archivesList.forEach(archives1 -> {
            archivesMapper.updateSeniority(archives1.getId());
        });

        //添加工作经历表
        int workNum = 0;
        List<WorkExperience> lists = new ArrayList<>();
        for (int rowNum = archivesLast + 1; rowNum < totalRows; rowNum++) {
            WorkExperience workExperience = new WorkExperience();
            Row row = sheet.getRow(rowNum);
            workNum = row.getRowNum();

            String employeeId = FilePortUtil.getValue(row.getCell(0));
            if (employeeId.equals("姓名") || employeeId.equals(" ")) {
                break;
            }
            workExperience.setEmployeeId(basicInfoMapper.selectOrgBasicId(getCurrentUserId(), employeeId));
            workExperience.setCompany(FilePortUtil.getValue(row.getCell(1)));
            workExperience.setDept(FilePortUtil.getValue(row.getCell(2)));
            workExperience.setTitle(FilePortUtil.getValue(row.getCell(3)));
            workExperience.setPost(FilePortUtil.getValue(row.getCell(4)));
            workExperience.setHiredate(sf.parse(FilePortUtil.getValue(row.getCell(5))));
            workExperience.setJobDescription(FilePortUtil.getValue(row.getCell(6)));
            lists.add(workExperience);
        }
        workExperienceService.batchInsert(lists);

        //导入教育表
        List<EducationalBackground> educationalBackgroundList = new ArrayList<>();
        for (int rowNum = workNum + 1; rowNum < totalRows; rowNum++) {
            EducationalBackground educationalBackground = new EducationalBackground();
            Row row = sheet.getRow(rowNum);

            String employeeId = FilePortUtil.getValue(row.getCell(0));
            if (employeeId.equals("姓名") || employeeId.equals(" ")) {
                break;
            }
            educationalBackground.setEmployeeId(basicInfoMapper.selectOrgBasicId(getCurrentUserId(), employeeId));
            educationalBackground.setSchool(FilePortUtil.getValue(row.getCell(1)));
            educationalBackground.setMajor(FilePortUtil.getValue(row.getCell(2)));
            educationalBackground.setEnterTime(sf.parse(FilePortUtil.getValue(row.getCell(3))));
            educationalBackground.setTimeCompletion(sf.parse(FilePortUtil.getValue(row.getCell(4))));
            educationalBackground.setEducation(FilePortUtil.getValue(row.getCell(5)));
            if (FilePortUtil.getValue(row.getCell(6)).equals("是")) {
                educationalBackground.setDegree(1);
            } else {
                educationalBackground.setDegree(0);
            }
            List<String> papersName = Arrays.asList(FilePortUtil.getValue(row.getCell(7)));
            educationalBackground.setPapersName(papersName);
            List<String> documentType = Arrays.asList(FilePortUtil.getValue(row.getCell(8)));
            educationalBackground.setDocumentType(documentType);
            List<String> documentNumber = Arrays.asList(FilePortUtil.getValue(row.getCell(9)));
            educationalBackground.setDocumentNumber(documentNumber);
            List<String> juniper = Arrays.asList(FilePortUtil.getValue(row.getCell(10)));
            educationalBackground.setJuniper(juniper);
            List<String> openingDate = Arrays.asList(FilePortUtil.getValue(row.getCell(11)));
            educationalBackground.setOpeningDate(openingDate);
            List<String> dateDue = Arrays.asList(FilePortUtil.getValue(row.getCell(12)));
            educationalBackground.setDateDue(dateDue);

            educationalBackgroundList.add(educationalBackground);
        }
        educationalBackgroundService.batchInsert(educationalBackgroundList);

        return JsonResult.success();
    }

    @ApiOperation(value = "导出空白模板")
    @RequestMapping(value = "nullFile", method = RequestMethod.GET)
    public JsonResult<Object> exportNullFile(HttpServletResponse response, String title) {
        excelService.exportNullFile(response, title);
        return JsonResult.success();
    }
}
